﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace MetadataBasedConfig.POCO
{
    public class EntityRepository<TEntity> : IRepository<TEntity>
        where TEntity : class,IEntity
    {
        #region Ctors

        public EntityRepository(DbContext context)
        {
            m_DbContext = context;
        }

        #endregion

        #region Entity Context

        protected readonly DbContext m_DbContext;

        public DbSet<TEntity> DbSet
        {
            get 
            {
                return m_DbContext.Set<TEntity>();
            }
        }

        #endregion

        #region

        public int Add(TEntity model)
        {
            m_DbContext.Set<TEntity>().Add(model);
            return m_DbContext.SaveChanges();
        }

        public int Update(TEntity model)
        { 
            return m_DbContext.SaveChanges();
        }

        public int Delete(TEntity model)
        {
            m_DbContext.Set<TEntity>().Remove(model);
            return m_DbContext.SaveChanges();
        }

        public IEnumerable<TEntity> Execute(Func<IEnumerable<TEntity>, IEnumerable<TEntity>> executeFunc)
        {
            return executeFunc(m_DbContext.Set<TEntity>());
        }

        public IEnumerable<TEntity> Find(Func<TEntity, bool> filterFunc)
        {
            return m_DbContext.Set<TEntity>().Where(filterFunc);
        }

        public IEnumerable<TEntity> FindAll()
        { 
            return   m_DbContext.Set<TEntity>();
        }
        #endregion


        public TEntity FindById(Int64 id)
        {
            return m_DbContext.Set<TEntity>().Where(t => t.ID == id).Single();
        }


        public TResult Excute<TResult>(System.Linq.Expressions.Expression<Func<IEnumerable<TEntity>, TResult>> expression)
        {
            return expression.Compile()(m_DbContext.Set<TEntity>());
        }
    }
}